import { Fragment, useEffect, useRef, useState } from "react";
import lessModule from "./index.module.less"
import { Checkbox, Radio } from "antd";

import HomePage_TagComponent from "../../../tag";
import HomePage_SingleBtnComponent from "../../../singleBtn";
import HomePage_DateTimePickerRangeComponent from "../../../dateTimePickerRange";
import { modeType } from "../../../../../../common/interface";
import { $eventBus, $EventBus_off, $EventBus_on } from "../../../../../../common/utils";
import HomePage_CardTitleComponent from "../../../cardtitle";
import { $Http } from "../../../../../../network";
import HomePage_DateTimePickerComponent from "../../../dateTimePicker";
import dayjs from "dayjs"
import { replace, useLocation, useNavigate } from "react-router-dom";
// 主页-分析组件-查看维度组件
interface homePageAnalysisComponentViewDimensionsComponentInterface {
    isTag?: boolean
    monitoringType?: string
    monitorModalName?: string
    mode?: modeType
    change_paramsData: Function
}
const HomePage_AnalysisComponent_ViewDimensionsComponent: React.FC<homePageAnalysisComponentViewDimensionsComponentInterface> = (props) => {
    const navigate = useNavigate()
    const location = useLocation()

    const tagItemList = [
        {
            name: "多主变同指标",
            dateType: "range",
            indexType: "radio",
            monitoringType: "主变",
            mode: "multiple" as modeType,
            tableName: "主变名称"
        },
        {
            name: "单主变多指标",
            dateType: "range",
            indexType: "check",
            monitoringType: "主变",
            mode: "single" as modeType,
            tableName: "指标名称"
        },
        {
            name: "单主变双时段",
            dateType: "ab",
            indexType: "radio",
            monitoringType: "主变",
            mode: "single" as modeType,
            tableName: "时段名称"
        },
        {
            name: "多线路同指标",
            dateType: "range",
            indexType: "radio",
            monitoringType: "线路",
            mode: "multiple" as modeType,
            tableName: "线路名称"
        },
        {
            name: "单线路多指标",
            dateType: "range",
            indexType: "check",
            monitoringType: "线路",
            mode: "single" as modeType,
            tableName: "指标名称"
        },
        {
            name: "单线路双时段",
            dateType: "ab",
            indexType: "radio",
            monitoringType: "线路",
            mode: "single" as modeType,
            tableName: "时段名称"
        },
    ]
    const mainIndexList = ["DC1", "AC", "NI", "VA", "EP1"]
    const timeList = ["10 min", "1 h", "4 h", "12 h", "24 h"]
    const lineIndexList = ["A相", "B相", "C相", "总和"]
    let [paramsData, setParamsData] = useState<object>({})
    const isIndex = useRef<boolean>(!(props.monitoringType === "线路" && props.mode === "multiple"))
    const [tagDateType, setTagDateType] = useState<string>(props.isTag ? tagItemList[0]["dateType"] : "")
    const [tagIndexType, setTagIndexType] = useState<string>(props.isTag ? tagItemList[0]["indexType"] : "")
    const [tagMode, setTagMode] = useState<modeType>(props.isTag ? tagItemList[0]["mode"] : null)
    let [tagTableName, setTagTableName] = useState<string>(props.isTag ? tagItemList[0]["tableName"] : "")

    const rowList = [{
        label: "时间",
        key: "time",
        type: props.isTag && !paramsData["tagName"]?.includes("双时段") ? tagDateType : "radio",
        children: timeList,
    },
    {
        label: "指标",
        key: "index",
        hide: !isIndex.current,
        type: props.isTag ? tagIndexType : props.mode === "multiple" ? "radio" : "check",
        children: paramsData["tagName"]?.includes("线路") || location["pathname"]?.includes("Line") ? lineIndexList : mainIndexList,
    },
    {
        label: props.monitoringType || paramsData["monitoringType"],
        type: props.mode || tagMode,
        key: "id"
    },]

    const click_tag = (data: object) => {
        paramsData["tagName"] = data["name"]
        paramsData["mode"] = data["mode"]
        paramsData["tableName"] = data["tableName"]
        paramsData["monitoringType"] = data["monitoringType"]
        paramsData["aStartTime"] = dayjs().subtract(1, 'hour').format('YYYY-MM-DD HH:mm:ss')
        if (paramsData["tagName"].includes("双时段")) {
            delete paramsData["aEndTime"]
            paramsData["bStartTime"] = dayjs().subtract(1, 'hour').format('YYYY-MM-DD HH:mm:ss')
            paramsData["time"] = timeList[0]
        } else {
            delete paramsData["bStartTime"]
            paramsData["aEndTime"] = dayjs().format('YYYY-MM-DD HH:mm:ss')
        }

        if (paramsData["tagName"].includes("线路")) {
            delete paramsData["index"]
        } else {
            paramsData["index"] = [mainIndexList[0]]
        }
        tagTableName = data["tableName"]
        setTagDateType(data["dateType"])
        setTagIndexType(data["indexType"])
        setTagMode(data["mode"])
        setTagTableName(tagTableName)

        
        http_search()
    }

    const change_choice = (event: any, type: string, key: string) => {
        switch (type) {
            case "check":
                paramsData[key] = event
                break;
            case "radio":
                paramsData[key] = key === "time" ? event.target.value : [event.target.value]
                break;
        }
        setParamsData({ ...paramsData })
        props.change_paramsData(paramsData)
    }

    const click_addMultipleTag = (data: object) => {
        setTimeout(() => {
            $eventBus.emit("openSelectMonitorModal", { mode: data["type"], operation: "监测", monitoringType: data["label"], modalName: `选择监测${data["label"]}`, selectedList: paramsData["deviceList"], selectedOtherList: paramsData["deviceOtherList"] })
        });
    }
    const click_delMultipleTag = (value: string) => {
        const idx = paramsData["deviceList"].indexOf(value)
        paramsData["deviceList"].splice(idx, 2)
        paramsData["deviceOtherList"].splice(idx, 2)
        paramsData["deviceIDList"].splice(idx, 2)
        setParamsData({ ...paramsData })
        props.change_paramsData(paramsData)
    }


    const change_picker = (key: string, date: string | Array<string>) => {
        paramsData[`${key}StartTime`] = date
        setParamsData({ ...paramsData })
        props.change_paramsData(paramsData)
    }
    const change_rangePicker = (list: Array<string>) => {
        paramsData["aStartTime"] = list[0]
        paramsData["aEndTime"] = list[1]
        setParamsData({ ...paramsData })
        props.change_paramsData(paramsData)
    }

    const http_search = () => {
        $Http("search", { typeName: `监测${location["state"]?.["type"] || paramsData["monitoringType"]}`, keyword: location["state"]?.["name"] ?? "" }).then((res) => {
            navigate(location["pathname"], { replace: true })
            paramsData["deviceOtherList"] = Object.keys(res["data"]["default"]).length ? [res["data"]["default"]] : []
            paramsData["deviceList"] = Object.keys(res["data"]["default"]).length ? [res["data"]["default"]["label"]] : []
            paramsData["deviceIDList"] = paramsData["deviceOtherList"].map((item: object) => item["deviceID"])
            isIndex.current = !((props.monitoringType === "线路" && props.mode === "multiple") || paramsData["tagName"] === "多线路同指标"
                || paramsData["deviceOtherList"].filter((item: object) => item["dataType"] === "回流线电流").length > 0)
            if (isIndex.current) {
                if (props.monitoringType === "主变" || paramsData["tagName"].includes("主变")) {
                    paramsData["index"] = [mainIndexList[0]]
                } else if (props.monitoringType === "线路" || paramsData["tagName"].includes("线路")) {
                    paramsData["index"] = [lineIndexList[0]]

                }
            }
            setParamsData({ ...paramsData })
            props.change_paramsData(paramsData)

        })
    }

    // 初始化paramsData
    const init_paramsData = () => {
        if (!props.isTag && !location.state) {
            paramsData = {
                tagName: "",
                tableName: "",
                monitoringType: props.monitoringType,
                time: timeList[0],
                index: [location["pathname"].includes("Line") ? lineIndexList[0] : mainIndexList[0]],
            }
            setParamsData({ ...paramsData })
        } else {
            if (location.state) {
                click_tag(tagItemList.filter((item: object) => item["name"] === location.state["tagName"])[0])
                navigate(location["pathname"], { replace: true })
            } else {
                click_tag(tagItemList[0])
            }
        }

    }
    // 广播函数数据
    const eventBusFuncData = {
        selectMonitorModalSelectedList: (data: object) => {
            paramsData["deviceList"] = data["data"]["selectedList"]
            paramsData["deviceOtherList"] = data["data"]["selectedOtherList"]
            paramsData["deviceIDList"] = paramsData["deviceOtherList"].map((item: object) => item["deviceID"])
            isIndex.current = !((props.monitoringType === "线路" && props.mode === "multiple") || paramsData["tagName"] === "多线路同指标"
                || paramsData["deviceOtherList"].filter((item: object) => item["dataType"] === "回流线电流").length > 0)
            if (isIndex.current) {
                if (props.monitoringType === "主变" || paramsData["tagName"].includes("主变")) {
                    paramsData["index"] = mainIndexList[0]
                } else if (props.monitoringType === "线路" || paramsData["tagName"].includes("线路")) {
                    paramsData["index"] = lineIndexList[0]

                }
            }

            setParamsData({ ...paramsData })
            props.change_paramsData(paramsData)
        },
    }

    useEffect(() => {
        init_paramsData()
        $EventBus_on(eventBusFuncData)
        http_search()
        return () => {
            $EventBus_off(eventBusFuncData)
        }
    }, [])

    return (
        <div className={lessModule["homePageAnalysisComponentViewDimensionsComponent"]}>
            {
                !props.isTag && <HomePage_CardTitleComponent title="查看维度" />
            }
            <main className={lessModule["homePageAnalysisComponentViewDimensionsComponent-main"]} style={{ paddingTop: props.isTag ? 87 : 0 }}>
                {
                    props.isTag && <div className={lessModule["homePageAnalysisComponentViewDimensionsComponent-main__tagCard"]}>
                        {
                            tagItemList.map((item, idx) => {
                                return (
                                    <div key={`tagItem${idx}`} className={lessModule["main-tagCard__tag"]} style={{
                                        background: item["name"] === paramsData["tagName"] ? "#1890FF" : "rgba(0,0,0,0)",
                                        color: item["name"] === paramsData["tagName"] ? "#FFFFFF" : "rgba(0, 0, 0, 0.65)",
                                        cursor: item["name"] === paramsData["tagName"] ? "default" : "pointer"
                                    }} onClick={() => item["name"] !== paramsData["tagName"] && click_tag(item)}>{item["name"]}</div>
                                )
                            })
                        }
                    </div>
                }
                {
                    tagDateType === "ab" && <div className={lessModule["homePageAnalysisComponentViewDimensionsComponent-main__startTimeCard"]}>
                        {
                            ["A", "B"].map((item, idx) => {
                                return (
                                    <div key={`item${idx}`} className={lessModule["main-startTimeCard__row"]}>
                                        <span>{item}开始时间：</span>
                                        <HomePage_DateTimePickerComponent value={dayjs(paramsData[`${idx ? "b" : "a"}StartTime`])} height={32} change_picker={(list: string | Array<string>) => change_picker(idx ? 'b' : "a", list)} />
                                    </div>
                                )
                            })
                        }
                    </div>
                }
                {
                    rowList.filter((item) => !item["hide"]).filter((item) => item["type"] && !["ab"].includes(item["type"])).map((item, idx) => {
                        return (
                            <div key={`rowItem${idx}`} className={lessModule["homePageAnalysisComponentViewDimensionsComponent-main__row"]} style={{ borderTop: idx ? "1px solid rgba(122, 143, 153, 0.2)" : "none" }}>
                                <div className={lessModule["main-row__label"]}>{item['label']}：</div>
                                {
                                    item["type"] === "check" && <Checkbox.Group
                                        options={item["children"]}
                                        value={paramsData[item["key"]]}
                                        onChange={(event) => change_choice(event, item["type"], item["key"])}
                                    />
                                }
                                {
                                    item["type"] === "radio" && <Radio.Group onChange={(event) => change_choice(event, item["type"], item["key"])} value={item["key"] === "time" ? paramsData[item["key"]] : paramsData[item["key"]]?.[0]}>
                                        {
                                            item["children"]?.map((item, idx) => {
                                                return (
                                                    <Radio key={`childrenItem${idx}`} value={item}>{item}</Radio>
                                                )
                                            })
                                        }
                                    </Radio.Group>
                                }
                                {
                                    item["type"] === "range" && <HomePage_DateTimePickerRangeComponent valueList={[paramsData["aStartTime"], paramsData["aEndTime"]]} width="100%" change_rangePicker={change_rangePicker} />
                                }
                                {
                                    item["type"] === "multiple" && <div className={lessModule["main-row__multipleTag"]}>
                                        {
                                            paramsData["deviceList"]?.map((item: string, idx: number) => {
                                                return (
                                                    <Fragment key={`childrenItem${idx}`}>
                                                        <HomePage_TagComponent name={item} click_del={click_delMultipleTag} />
                                                    </Fragment>
                                                )
                                            })
                                        }
                                        <div className={lessModule["row-multipleTag__add"]} onClick={() => click_addMultipleTag(item)}>
                                            <span>+</span>
                                            <span>添加</span>
                                        </div>
                                    </div>
                                }
                                {
                                    item["type"] === "single" && <HomePage_SingleBtnComponent operation="监测" selectedValue={paramsData["deviceList"]?.[0]} minWidth={151} monitoringType={props.monitoringType || paramsData["monitoringType"]} monitorModalName={props.monitorModalName || `选择监测${paramsData["monitoringType"]}`} />
                                }
                            </div>
                        )
                    })
                }
            </main >
        </div >
    )
}


export default HomePage_AnalysisComponent_ViewDimensionsComponent